<?php
global $_W,$_GPC;
$did = $_GPC['did'];
$op = $_GPC['op'] ? $_GPC['op'] : 'display';
$weid = $_W['uniacid'];

$directory = get('select * from '.tb('book_directory')." where id='{$did}' and uniacid='{$weid}'");
if (empty($directory)) MSG('目录不存在',referer(),'error');
if($op == 'display'){
	$condition = '';
	$pindex = max(1,$_GPC['page']);
	$psize = 20;
	
	$title = $_GPC['title'];
	if(!empty($title)){
		$condition .= " and title like '%{$title}%'";
	}
	$list = getall('select * from '.tb('book_question')." where uniacid='{$weid}' and did='{$did}' {$condition} order by sort desc, id asc limit ".($pindex-1)*$psize.','.$psize);
	
	$total = col('select count(1) from ' . tb('book_question') . " where uniacid='{$weid}' and did='{$did}' {$condition}");
	$pager = pagination($total, $pindex, $psize);
}
		
if($op == 'post'){
	$id = intval($_GPC['id']);
	if ($id){
		$item = get('select * from '.tb('book_question')." where id='{$id}'");
		$item['detail'] = unserialize($item['detail']);
	}
	
	if (checksubmit()){
		$detail = array();
		$detail_title = $_GPC['detail'];
		if(!empty($detail_title)){
			foreach ($detail_title as $k => $v){
				if(!empty($v)){
					$detail[] = [
							'title' => $v,
							'issure' => $_GPC['issure'][$k]
					];
				}
			}
		}
		$data = array(
			'title' => trim($_GPC['title']),
			'sort' => trim($_GPC['sort']),
			'remark' => trim($_GPC['remark']),
			'detail' => serialize($detail),
		);
		if ($item){
			update('book_question',$data,array('id'=>$id));
		}else{
			$data['bid'] = $directory['bid'];
			$data['did'] = $did;
			$data['uniacid'] = $weid;
			insert('book_question', $data);
		}
		MSG('操作成功',$this->wurl('question',array('op'=>'display','did'=>$did)),'success');
	}
}
		
if($op == 'del'){
	$id = $_GPC['id'];
	$item = get('select * from ' . tb('book_question') . " where id = '{$id}'");
	if(empty($item)){
		MSG('该记录不存在或已被删除',$this->wurl('question',array('did'=>$did)),'error');
	}
	if(del('book_question',array('id'=>$id)) === false) MSG('操作失败',referer(),'error');
	else MSG('操作成功',$this->wurl('question',array('did'=>$did)),'success');
}
include $this->template('question');